from django.http import HttpResponse
from django.shortcuts import render, redirect


# Create your views here.
from . import models


def login(request):
    if request.method == 'GET':
        if request.session.get('is_login',None):
            return redirect('/user/index')
        return render (request,'login.html')
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        try:
            user = models.User.objects.get(username=username,is_active=True)
        except Exception as e:
            message = '用户名不存在'
            return render(request,'login.html',{'message':message})
        if user.password == password:
            request.session['is_login'] = True
            request.session['username'] = user.username
            request.session['userid'] = user.id
            resp = redirect('/user/index')
            if 'remember' in request.POST:
                resp.set_cookie('is_login',True,3600*24)
                resp.set_cookie('username',user.username,3600*24)
                resp.set_cookie('userid',user.id,3600*24)
            return resp
        else:
            message = '密码错误'
            return render(request,'login.html',{'message':message})
    return render(request, 'login.html')

def logout(request):
    if request.session.get('is_login',None):
        request.session.flush()
    resp = redirect('/user/index')
    if 'is_login' in request.COOKIES:
        resp.delete_cookie('is_login')
    if 'username' in request.COOKIES:
        resp.delete_cookie('username')
    if 'userid' in request.COOKIES:
        resp.delete_cookie('userid')
    return resp


def index(request):
    return render(request,'index.html')
